一、學習目標
本日目標是讓使用者可以上傳一張圖片並即時預覽,體驗基本的圖片顯示功能。這是線上相簿的核心功能之一,能讓使用者確認上傳內容是否正確。
二、學習過程與方法
我使用 <input type="file"> 元素讓使用者選取圖片,並用 JavaScript 的 FileReader() 物件來讀取檔案內容,再將其轉成 Base64 格式顯示在頁面上。這樣可以避免伺服器端儲存,提升開發效率。
三、實作成果
上傳後圖片會立即出現在相簿區,不用重新整理頁面。整個流程順暢,並確保支援常見格式如 JPG、PNG、GIF。這是奠定使用者互動體驗上的第一個里程碑。
四、主要程式碼區塊
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>Day3 - 單張圖片上傳與預覽</title>
<style>
/*統一主題配色*/
:root {
--bg: #ffffff;
--primary: darkorange;
--accent: coral;
--text: #333;
--muted: #777;
--border: #e6e6e6;
--btn: #ff8c42;
--btn-hover: #ff6a00;
--card-bg: #fff;
}
/*基本結構樣式*/
body {
background-color: var(--bg);
font-family: "Microsoft JhengHei", Arial, sans-serif;
margin: 20px;
text-align: center;
color: var(--text);
}
h1 {
color: var(--primary);
}
p {
color: var(--accent);
font-size: 18px;
}
/*上傳區*/
input[type="file"] {
margin: 15px 0;
padding: 8px;
border-radius: 6px;
border: 1px solid var(--border);
font-size: 16px;
cursor: pointer;
}
/*圖片展示區*/
#gallery {
display: flex;
justify-content: center;
margin-top: 20px;
}
.photo-card {
background: var(--card-bg);
border: 1px solid var(--border);
border-radius: 10px;
padding: 10px;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
width: 300px;
}
.photo-card img {
width: 100%;
border-radius: 8px;
border: 2px solid #ddd;
}
.info {
font-size: 14px;
color: var(--muted);
margin-top: 8px;
word-wrap: break-word;
overflow-wrap: anywhere;
}
</style>
</head>
<body>
<h1>我的線上相簿</h1>
<p>Day3:單張圖片上傳與即時預覽功能</p>
<!--圖片上傳按鈕-->
<input type="file" id="upload" accept="image/*">
<!--圖片展示區-->
<div id="gallery"></div>
<script>
const upload = document.getElementById("upload");
const gallery = document.getElementById("gallery");
// 當使用者選擇圖片後觸發
upload.addEventListener("change", function() {
const file = this.files[0]; // 只處理第一張
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const img = new Image();
img.onload = function() {
// 建立圖片卡片
const card = document.createElement("div");
card.classList.add("photo-card");
// 建立圖片元素
const newImg = document.createElement("img");
newImg.src = e.target.result;
// 產生簡短檔名
const shortName = file.name.length > 25 ? file.name.slice(0, 25) + "..." : file.name;
// 建立資訊文字
const info = document.createElement("p");
info.classList.add("info");
info.textContent =
`檔名: ${shortName} | 大小: ${(file.size / 1024).toFixed(1)} KB | 尺寸: ${img.width}x${img.height}`;
// 組合顯示卡片
card.appendChild(newImg);
card.appendChild(info);
gallery.innerHTML = ""; // 清空舊圖片,只顯示最新上傳的
gallery.appendChild(card);
};
img.src = e.target.result;
};
reader.readAsDataURL(file); // 將圖片轉為 base64
}
});
console.log("Day3:單張圖片上傳與即時預覽完成");
</script>
</body>
</html>
